package com.shiku.imserver.repository;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.shiku.imserver.common.IService;
import com.shiku.imserver.common.message.ChatMessage;
import com.shiku.imserver.common.utils.Callback;
import com.shiku.imserver.common.utils.ThreadUtil;
import com.shiku.imserver.service.IMBeanUtils;
import com.shiku.utils.StringUtil;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServiceRepository extends BaseRepository implements IService {
    private static final String CONFIG = "config";
    private static final String INTERCEPTKEYWORD = "msgIntercept";
    private static final String NEWFRIENDS = "shiku_newFirend";
    private static final String NOTKEYWORD = "keyWord";
    private static Logger logger = LoggerFactory.getLogger(ServiceRepository.class);
    private Set<String> allKeyWord = new HashSet();
    private MongoClientURI mongoApiUri;
    private MongoClient mongoClient;
    private MongoDatabase newFriendDB;

    public boolean initialize() {
        try {
            getMongoClient();
            getAllKeyWord();
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public void saveInterceptKeyWord(String userId, String toUserId, String roomJid, String content) {
        Document dbObj = new Document();
        dbObj.put("sender", Long.valueOf(userId));
        if (StringUtil.isEmpty(userId)) {
            dbObj.put("receiver", Long.valueOf(toUserId));
        }
        if (!StringUtil.isEmpty(roomJid)) {
            dbObj.put("roomJid", roomJid);
        }
        dbObj.put("content", content);
        dbObj.put("createTime", Long.valueOf(System.currentTimeMillis()));
        getCollection(INTERCEPTKEYWORD).insertOne(dbObj);
    }

    public String filterKeyWord(ChatMessage message) {
        if (StringUtil.isEmpty(message.getContent())) {
            return null;
        }
        boolean match = false;
        String keyWord = null;
        Iterator<String> it = this.allKeyWord.iterator();
        while (true) {
            if (!it.hasNext()) {
                break;
            }
            String str = it.next();
            if (message.getContent().toLowerCase().contains(str)) {
                keyWord = str;
                match = true;
                break;
            }
        }
        if (!match) {
            return keyWord;
        }
        if (2 == message.getMessageHead().getChatType()) {
            saveInterceptKeyWord(message.getFromUserId(), null, message.getToUserId(), message.getContent());
            return keyWord;
        }
        saveInterceptKeyWord(message.getFromUserId(), message.getToUserId(), null, message.getContent());
        return keyWord;
    }

    public Set<String> getAllKeyWord() {
        MongoCursor<Document> iterator = getCollection(NOTKEYWORD).find().iterator();
        Set<String> keyWords = new HashSet<>();
        while (iterator.hasNext()) {
            Document dbObj = (Document) iterator.next();
            if (dbObj != null) {
                keyWords.add(dbObj.get("word").toString().toLowerCase());
            }
        }
        this.allKeyWord = keyWords;
        return keyWords;
    }

    private MongoCollection getCollection(String dbName) {
        if (this.mongoClient != null) {
            return this.mongoClient.getDatabase(this.mongoApiUri.getDatabase()).getCollection(dbName);
        }
        return getMongoClient().getDatabase(this.mongoApiUri.getDatabase()).getCollection(dbName);
    }

    private MongoClient getMongoClient() {
        try {
            if (this.mongoClient != null) {
                return this.mongoClient;
            }
            String apiUri = IMBeanUtils.getImconfig().getMongoConfig().getApiUri();
            if (apiUri == null) {
                apiUri = IMBeanUtils.getImconfig().getMongoConfig().getUri();
            }
            System.out.println("mongoClient  is ---null");
            MongoClientOptions.Builder builder = MongoClientOptions.builder();
            builder.socketKeepAlive(true);
            builder.socketTimeout(20000);
            builder.connectTimeout(20000);
            builder.maxWaitTime(12000000);
            builder.heartbeatFrequency(2000);
            this.mongoApiUri = new MongoClientURI(apiUri);
            this.mongoClient = new MongoClient(this.mongoApiUri);
            return this.mongoClient;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private void initConfig() {
        int xmppTimeout = getConfig().getInteger("XMPPTimeout").intValue();
        if (xmppTimeout == 0) {
            xmppTimeout = 180;
        }
        int xmppTimeout2 = xmppTimeout * 1000;
    }

    public boolean getKeyWord(String keyword) {
        MongoCollection<Document> dbCollection = getCollection(NOTKEYWORD);
        Document query = new Document();
        query.put("word", new Document("$regex", keyword));
        return dbCollection.count(query) > 0;
    }

    public Document getConfig() {
        Document keys = new Document();
        keys.put("XMPPTimeout", 1);
        keys.put("isSaveMsg", 1);
        keys.put("isSaveMucMsg", 1);
        keys.put("isMsgSendTime", 1);
        keys.put("isKeyWord", 1);
        Document obj = (Document) getCollection(CONFIG).find(new Document()).projection(keys).first();
        logger.info("getConfig ", obj.toJson());
        return obj;
    }

    public void saveNewFriendsInThread(final long userId, final long toUserId, final Object from, final int direction, final int type, final String content) {
        ThreadUtil.executeInThread(new Callback() {
            /* class com.shiku.imserver.repository.ServiceRepository.AnonymousClass1 */

            public void execute(Object obj) {
                ServiceRepository.this.saveNewFriends(userId, toUserId, from, direction, type, content);
            }
        });
    }

    public void saveNewFriends(long userId, long toUserId, Object from, int direction, int type, String content) {
        Document query = new Document("userId", Long.valueOf(userId));
        query.put("toUserId", Long.valueOf(toUserId));
        MongoCollection<Document> collection = getCollection(this.newFriendDB, userId);
        Document dbObj = new Document();
        Document obj = (Document) collection.find(query).first();
        long modifyTime = System.currentTimeMillis() / 1000;
        if (content == null) {
            content = "";
        }
        if (500 == type) {
            dbObj.put("from", from);
        }
        if (obj == null) {
            dbObj.put("userId", Long.valueOf(userId));
            dbObj.put("toUserId", Long.valueOf(toUserId));
            dbObj.put("direction", Integer.valueOf(direction));
            dbObj.put("createTime", Long.valueOf(modifyTime));
            dbObj.put("modifyTime", Long.valueOf(modifyTime));
            dbObj.put("type", Integer.valueOf(type));
            dbObj.put("content", content);
            collection.insertOne(dbObj);
            return;
        }
        dbObj.put("content", content);
        dbObj.put("direction", Integer.valueOf(direction));
        dbObj.put("type", Integer.valueOf(type));
        dbObj.put("content", content);
        dbObj.put("modifyTime", Long.valueOf(modifyTime));
        collection.updateOne(query, new Document("$set", dbObj));
    }
}
